import xml.sax.handler
import os.path
import sys

# Basic SAX (XML parser) handler to parse XML map files
class MapHandler(xml.sax.handler.ContentHandler):
	def __init__(self):
	        self.inMap = self.inTileset = self.inImage = self.inPassable = False
		self.passable = {}
		self.tile_key = {}
		self.map = []
		self.base_path = sys.path[0]

		
	def startElement(self, name, attributes):
		if name == "tileset":
			self.inTileset = True
		elif name == "map":
			self.inMap = True
		if self.inTileset:
			if name == "tile":
				self.id = attributes["id"]
			elif name == "image":
				self.buffer = ""
				self.inImage = True
			elif name == "passable":
				self.buffer = ""
				self.inPassable = True

	def characters(self, data):
		if self.inTileset:
			if self.inImage or self.inPassable:
				self.buffer += data
		elif self.inMap:
			line = data.strip()
			if line != '':
				self.map.append([x for x in line if x != ','])

	def endElement(self, name):
		if name == "tileset":
			self.inTileset = False
		elif name == "map":
			self.inMap = False
					
		if self.inTileset:
			if name == "image":
				self.inImage = False
				cur_path = os.path.join(self.base_path, *self.buffer.split('/'))
				self.tile_key[self.id] = cur_path
			elif name == "passable":
				self.inPassable = False
				self.passable[self.id] = bool(int(self.buffer))
